#!/bin/bash

: << !
  version: 0.0.1
  DOTO: 
      - 需要解决包下载慢，更新问题
      - 需要解决使用参数转递来区分不同ID的配置
      - 需要解决配置文件更新问题
      - 需要解决系统重启
!

# PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
# export PATH

bail() {
  echo -e "\033[31mError executing command, exiting.\033[0m"
  exit 1
}

exec_cmd_nobail() {
  echo "+ $1"
  bash -c "$1"
}

exec_cmd() {
  exec_cmd_nobail "$1" || bail
  wait
}

# 判断是否使用root运行
if [ "$UID" != "0" ]; then
  echo -e "\033[31mPlease run this script by root!\033[0m"
  bail
fi;

ABSPATH=$(cd "$(dirname '$0')";pwd);
VERSION="0.0.1"
DEPLOY_DIR="${ABSPATH}/deploy"

# 下载相关文件配置
DOWNLOAD_URL="https://taimei-ftp.oss-cn-shenzhen.aliyuncs.com"
DEPLOY_DOWNLOAD_URL="${DOWNLOAD_URL}/ors"
DEPLOY_ENV_FILE="${DEPLOY_DIR}/env.sh"
DEPLOY_BOOTSTRAP_FILE="${DEPLOY_DIR}/bootstrap.sh"

download_deploy() {
  if [ ! -d $DEPLOY_DIR ]; then
    exec_cmd "mkdir -p $DEPLOY_DIR"
  fi;

  if [ ! -f $DEPLOY_ENV_FILE ]; then
    download_url=${DEPLOY_ENV_FILE/${ABSPATH}/${DEPLOY_DOWNLOAD_URL}}
    exec_cmd "curl --progress -o ${DEPLOY_ENV_FILE} ${download_url}"
    unset download_url
  fi;

  if [ ! -f $DEPLOY_BOOTSTRAP_FILE ]; then
    download_url=${DEPLOY_BOOTSTRAP_FILE/${ABSPATH}/${DEPLOY_DOWNLOAD_URL}}
    exec_cmd "curl --progress -o ${DEPLOY_BOOTSTRAP_FILE} ${download_url}"
    unset download_url
  fi;
}

download_deploy

exec_cmd "sh ${DEPLOY_BOOTSTRAP_FILE} $1"
